import type { PlanetData, Position } from '../types';

/**
 * 计算行星当前位置
 * @param planet 行星数据
 * @param time 当前时间
 * @param speed 动画速度
 * @param centerX 中心X坐标
 * @param centerY 中心Y坐标
 * @returns 行星位置
 */
export function calculatePlanetPosition(
  planet: PlanetData,
  time: number,
  speed: number,
  centerX: number,
  centerY: number
): Position {
  const angle = (time * speed * 2 * Math.PI) / (planet.orbitPeriod * 1000) + planet.initialAngle;
  return {
    x: centerX + planet.orbitRadius * Math.cos(angle),
    y: centerY + planet.orbitRadius * Math.sin(angle)
  };
}

/**
 * 颜色变亮函数
 * @param color 原始颜色
 * @param amount 变亮程度
 * @returns 变亮后的颜色
 */
export function lightenColor(color: string, amount: number = 40): string {
  const hex = color.replace('#', '');
  const r = Math.min(255, parseInt(hex.substr(0, 2), 16) + amount);
  const g = Math.min(255, parseInt(hex.substr(2, 2), 16) + amount);
  const b = Math.min(255, parseInt(hex.substr(4, 2), 16) + amount);
  return `rgb(${r}, ${g}, ${b})`;
}

/**
 * 颜色变暗函数
 * @param color 原始颜色
 * @param amount 变暗程度
 * @returns 变暗后的颜色
 */
export function darkenColor(color: string, amount: number = 40): string {
  const hex = color.replace('#', '');
  const r = Math.max(0, parseInt(hex.substr(0, 2), 16) - amount);
  const g = Math.max(0, parseInt(hex.substr(2, 2), 16) - amount);
  const b = Math.max(0, parseInt(hex.substr(4, 2), 16) - amount);
  return `rgb(${r}, ${g}, ${b})`;
}

/**
 * 节流函数
 * @param func 要节流的函数
 * @param delay 延迟时间
 * @returns 节流后的函数
 */
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeoutId: number | null = null;
  let lastExecTime = 0;
  
  return (...args: Parameters<T>) => {
    const currentTime = Date.now();
    
    if (currentTime - lastExecTime > delay) {
      func(...args);
      lastExecTime = currentTime;
    } else {
      if (timeoutId) {
        clearTimeout(timeoutId);
      }
      timeoutId = window.setTimeout(() => {
        func(...args);
        lastExecTime = Date.now();
      }, delay - (currentTime - lastExecTime));
    }
  };
}